<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">

        <el-col :span="24" class="mb20">
          <el-form-item label="模块" prop="moduleId">

            <el-select v-model="form.moduleId" placeholder="请选择模块" @change="changeModuleInfo" :disabled="form.id!==''">
              <el-option :label="moduleInfo.name" :value="moduleInfo.id"
                         v-for="moduleInfo in moduleInfoList "></el-option>
            </el-select>

          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="分支" prop="branchId">
            <el-select v-model="form.branchId" placeholder="请选择分支" >
              <el-option :label="branchInfo.name" :value="branchInfo.id"
                         v-for="branchInfo in branchInfoList "></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="容器名" prop="containerName">
            <el-input v-model="form.containerName" placeholder="请输入容器名"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="配置json" prop="configJson">
            <el-input v-model="form.configJson" placeholder="请输入配置json"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="服务器" prop="serverModuleInfoId">
            <!--        <el-input v-model="form.serverIp" placeholder="请输入服务器ip"/>-->
            <el-select v-model="form.serverModuleInfoId" placeholder="请选择服务器">
              <el-option :label="serverModuleInfo.serverIp + ':' + serverModuleInfo.serverPort"
                         :value="serverModuleInfo.id" v-for="serverModuleInfo in serverModuleInfoList "></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20" v-if="form.id!==''">
          <el-form-item label="服务器ip" prop="serverIp"  >
            <el-input v-model="form.serverIp"   disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20" v-if="form.id!==''">
          <el-form-item label="服务器端口" prop="serverPort">
            <el-input v-model="form.outServerPort"  disabled/>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="deployDeplDockerInfoDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, edit,active} from '/@/api/bms/deploy/dockerInfo'
import {listAllModuleInfo} from "/@/api/bms/deploy/moduleInfo";
import {listAllBranchInfo} from "/@/api/bms/deploy/branchInfo";
import {listByModule} from "/@/api/bms/deploy/serverModuleInfo";
import {rule} from '/@/utils/validate';

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const {docker_info_status} = useDict('docker_info_status')

// 提交表单数据
const form = reactive({
  id: '',
  containerId: '',
  moduleId: '',
  branchId: '',
  containerName: '',
  configJson: '',
  serverModuleInfoId: ''
});

// 定义校验规则
const dataRules = ref({
  containerId: [{required: true, message: '容器id不能为空', trigger: 'blur'}],
  moduleId: [{required: true, message: '模块id不能为空', trigger: 'blur'}],
  branchId: [{required: true, message: '分支id不能为空', trigger: 'blur'}],
  containerName: [{required: true, message: '容器名不能为空', trigger: 'blur'}],
  configJson: [{required: true, message: '配置json不能为空', trigger: 'blur'}],
  serverModuleInfoId: [{required: true, message: '服务器ip不能为空', trigger: 'blur'}],
})

// 打开弹窗
const openDialog = async (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取dockerInfo信息
  if (id) {
    form.id = id
    await getDockerInfoData(id)
    await changeModuleInfo()
  }else{
    serverModuleInfoList.value = []
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;
  console.log("onSubmit", form)
  // return;
  try {
    loading.value = true;
    form.id ? await edit(form) : await active(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
// 修改 getDockerInfoData 返回 Promise
const getDockerInfoData = (id: string) => {
  return new Promise((resolve) => {  // 返回 Promise
    loading.value = true
    getObj(id).then((res: any) => {
      Object.assign(form, res.data)
      resolve(res.data)  // 请求完成后 resolve
    }).finally(() => {
      loading.value = false
    })
  })
};

// 暴露变量
defineExpose({
  openDialog
});


//加载所有模块信息
const moduleInfoList = ref([])  // 模块信息列表
const loadModuleInfoList = async () => {
  const res = await listAllModuleInfo()
  moduleInfoList.value = res.data
  console.log("moduleInfoList", moduleInfoList.value)
}
loadModuleInfoList()

//加载所有分支信息
const branchInfoList = ref([])  // 分支信息列表
const loadBranchInfoList = async () => {
  const res = await listAllBranchInfo()
  branchInfoList.value = res.data
  console.log("branchInfoList", branchInfoList.value)
}
loadBranchInfoList()

const serverModuleInfoList = ref([])  // 分支信息列表
const changeModuleInfo = async () => {
  const res = await listByModule(form.moduleId)
  serverModuleInfoList.value = res.data
  if(form.id===''){
    form.serverModuleInfoId = serverModuleInfoList.value[0].id
  }else{
    serverModuleInfoList.value.forEach((serverModuleInfo:any)=>{
      if(serverModuleInfo.serverIp === form.serverIp && serverModuleInfo.serverPort === form.outServerPort){
        form.serverModuleInfoId = serverModuleInfo.id
      }
    })
  }

  console.log("serverModuleInfoList", serverModuleInfoList.value)
}

</script>
